package com.wisemoresystem.seal.util.abchinaFinger.common;

import java.io.UnsupportedEncodingException;

public class StringUtil {
	
	static final String DEFAULTCHARSET = "GBK";
	static public String ALIGNLEFT = "LEFT";
	static public String ALIGNRIGHT = "RIGHT";

	public static String getFixedLengthString(String srcString, int Length)
			throws UnsupportedEncodingException {
		return getFixedLengthString(srcString, Length, ' ', ALIGNLEFT);
	}

	public static int trimLeftGBK(String srcString, int n)
			throws UnsupportedEncodingException {
		boolean bChinaFirstHalf = false;
		byte[] buf = srcString.getBytes(DEFAULTCHARSET);
		if (buf.length == srcString.length())
			return n;
		int num = 0;
		for (int i = 0; i < n; i++) {
			if (buf[i] < 0 && !bChinaFirstHalf)
				bChinaFirstHalf = true;
			else {
				bChinaFirstHalf = false;
				num++;
			}
		}
		return num;
	}

	public static int trimRightGBK(String srcString, int n)
			throws UnsupportedEncodingException {
		boolean bChinaFirstHalf = false;
		byte[] buf = srcString.getBytes(DEFAULTCHARSET);
		if (buf.length == srcString.length())
			return n;
		int num = 0;
		int nLen = buf.length - 1;
		for (int i = 0; i < n; i++) {
			if (buf[nLen - i] < 0 && !bChinaFirstHalf)
				bChinaFirstHalf = true;
			else {
				bChinaFirstHalf = false;
				num++;
			}
		}
		return srcString.length() - num;
	}

	public static String getFixedLengthString(String srcString, int Length,
			char fillChar, String leftOrRight)
			throws UnsupportedEncodingException {
		String szResult = "";
		if (!leftOrRight.equals(ALIGNLEFT)) {
			if (Length >= srcString.getBytes(DEFAULTCHARSET).length)
				szResult = initString(fillChar,
						Length - srcString.getBytes(DEFAULTCHARSET).length)
						.concat(srcString);
			else {
				szResult = srcString.substring(trimRightGBK(srcString, Length));
			}
		} else {
			if (Length >= srcString.getBytes(DEFAULTCHARSET).length)
				szResult = srcString.concat(initString(fillChar, Length
						- srcString.getBytes(DEFAULTCHARSET).length));

			else {
				szResult = srcString.substring(0,
						trimLeftGBK(srcString, Length));
			}
		}
		return szResult;
	}

	public static String initString(char fillChar, int count) {
		StringBuffer sbResult = new StringBuffer();
		for (int i = 0; i < count; i++) {
			sbResult.append(fillChar);
		}
		return sbResult.toString();
	}

}
